<template>
	<div class="m-text">

		<ul class="tool overflow">
			<li class="picture">
				<input type="file" id="file-input" @change="selectImg($event)" />
				<img src="./assets/picture.png" alt="" />
			</li>
			<li @click="showEmoji">
				<img src="./assets/face.png" alt="" />
			</li>
		</ul>

		<!--<li @click="setData">sadfasdf</li>
		<div v-html="html">-->
		<!--</div>-->
		<!--{{text}}-->
		<!--<img src="assets/faces/ee_1.png" style="width: 20px;height: 20px;" alt="" />-->
		<div class="textarea">
			<ul class="overflow faces">
				<li v-for="(value,key) in Emoji.map" style="float: left;" class="hover" @click="addEmoji(value,key)">
					<img :src="require('./assets/faces/'+value)" />		
				</li>
			</ul>
			<!--{{textPicture}}-->
			<!--<div class="content" id="content" v-html="text"  contenteditable="true" @input="changeValue($event)"></div>-->
			<textarea placeholder="按 Ctrl + Enter 发送" v-model="text" @keyup="inputing"></textarea>
		</div>
		<div class="submit hover" @click="submit">发送</div>
	</div>
</template>

<script>
	import $ from 'jquery';
	export default {
		props: ['session', 'parent_data', 'conn'],
		data() {
			return {
				text: '',
				textPicture: '',
				p1: require('./assets/faces/ee_1.png'),
				Emoji: WebIM.Emoji,
				html: null
			};
		},
		mounted() {
			console.log(WebIM.Emoji)
			setTimeout(() => {
				//				let str = `<img src="${this.p1}" style="width: 20px;height: 20px;" alt="" />`
				//				this.text = str;
			}, 100)
			this.setData()
		},
		methods: {
			inputing(e) {
				if(e.ctrlKey && e.keyCode === 13 && this.text.length) {
					this.session.messages.push({
						text: this.text,
						date: new Date(),
						self: true
					});
					this.text = '';

				}
			},
			selectImg(ev) {
				console.log(ev)
				this.sendPrivateImg(ev.target)
			},
			showEmoji(){
				$('.faces').slideDown();
			},
			sendPrivateImg(target) {
				let self = this;
				var id = conn.getUniqueId(); // 生成本地消息id
				var msg = new WebIM.message('img', id); // 创建图片消息
				var input = target; // 选择图片的input
				var file = WebIM.utils.getFileUrl(input); // 将图片转化为二进制文件
				var allowType = {
					'jpg': true,
					'gif': true,
					'png': true,
					'bmp': true,
					'jpeg': true,
				};
				if(file.filetype.toLowerCase() in allowType) {
					var option = {
						apiUrl: WebIM.config.apiURL,
						file: file,
						to: self.session.name, // 接收消息对象
						roomType: false,
						chatType: 'singleChat',
						onFileUploadError: function() { // 消息上传失败
							console.log('onFileUploadError');
						},
						onFileUploadComplete: function() { // 消息上传成功
							console.log('onFileUploadComplete');
							self.session.messages.push({
								text: file.url,
								date: new Date(),
								type: 2,
								self: true
							})
							setTimeout(() => {
								target.value = null;
							}, 100)
						},
						success: function() { // 消息发送成功
							console.log(file);

						},
						flashUpload: WebIM.flashUpload
					};
					msg.set(option);
					conn.send(msg.body);
				}
			},
			getFaces() {
				let str = this.text;
				var r = /\[(.+?)\]/g;
				console.log(str)
				var m = str.match(r);
				if(m && m.length > 0) {
					for(let item of m) {
						if(str.indexOf(item) > -1) {
							if(this.Emoji.map[item]) {
								let p = require('./assets/faces/' + this.Emoji.map[item]);
								let pre = `<img src="${p}" class="emoji"  />`
								str = str.replace(item, pre)
							}
						}
					}
					return str;
				}
				return str;
			},
			submit() { // 单聊发送文本消息
				let self = this;
				var id = conn.getUniqueId(); // 生成本地消息id
				var msg = new WebIM.message('txt', id); // 创建文本消息
				msg.set({
					msg: self.text, // 消息内容
					to: self.session.name, // 接收消息对象（用户id）
					roomType: false,
					success: function(id, serverMsgId) {
						console.log('send private text Success');
						this.$message.success(serverMsgId);
					},
					fail: function(e) {
						console.log("Send private text error");
					}
				});
				msg.body.chatType = 'singleChat';
				conn.send(msg.body);
				this.session.messages.push({
					text: this.getFaces(),
					date: new Date(),
					type: 1,
					self: true
				});
				this.text = '';
			},
			addEmoji(value, key) {
				let p = require('./assets/faces/' + value);
				//				this.textPicture +=  `<img src="${p}" />`		
				this.textPicture += key;
				this.text += key;
				console.log(this.textPicture);
				$('.faces').slideUp();
			},
			changeValue(ev) {
				//				console.log(ev.target.innerText)
				this.text = ev.target.innerHTML;
				this.textPicture = ev.target.innerHTML;
				setTimeout(() => {
					this.set_focus()
				}, 0)
			},
			set_focus() {
				let el = document.getElementById('content');
				//el=el[0];  //jquery 对象转dom对象
				el.focus();
				if($.support.msie) {
					var range = document.selection.createRange();
					this.last = range;
					range.moveToElementText(el);
					range.select();
					document.selection.empty(); //取消选中
				} else {
					var range = document.createRange();
					range.selectNodeContents(el);
					range.collapse(false);
					var sel = window.getSelection();
					sel.removeAllRanges();
					sel.addRange(range);
				}
			},
			setData() {
				let arr_ = [{
					type: "txt",
					data: "1"
				}, {
					type: "emoji",
					data: "demo/images/faces/ee_9.png"
				}]
				let pre = ''
				let arr = arr_.map(item => {
					if(item.type == 'txt') {
						return item;
					} else if(item.type == 'emoji') {
						let ar = item.data.split('/')
						console.log(ar)
						return {
							type: item.type,
							data: ar[ar.length - 1]
						}
					}
				})

				for(let item of arr) {
					if(item.type == 'txt') {
						pre += item.data
					} else if(item.type == 'emoji') {
						let p = require('./assets/faces/' + item.data);
						pre += `<img src="${p}" style="width: 20px;height: 20px;"  />`
					}
				}

				this.html = pre;
				console.log(arr)

			}
		}
	};
</script>

<style lang="less">
	.emoji{
		width: 20px;
		height: 20px;
		vertical-align: middle;
	}
	.m-text {
		height: 190px;
		border-top: solid 1px #ddd;
		position: relative;
		padding-top: 5px;
		.textarea {
			position: relative;
			height: 160px;
			width: 100%;
			padding: 10px;
			margin-top: 5px;
			textarea {
				position: absolute;
				left: 0;
				top: 0;
				padding: 10px;
				height: 100%;
				width: 100%;
				border: none;
				outline: none;
				font-family: "Micrsofot Yahei";
				resize: none;
				background-color: transparent;
			}
			.content {
				position: absolute;
				left: 0;
				top: 0;
				padding: 10px;
				z-index: 11;
				height: 100%;
				width: 100%;
				&:focus {
					border: none;
					outline: none;
				}
			}
			.faces {
				display: none;
				position: absolute;
				bottom: ~'calc(100% + 32px)';
				left: 0;
				width: 224px;
				z-index: 1111;
			}
		}
		.submit {
			background-color: #eee;
			color: #222;
			padding: 4px 30px;
			font-size: 14px;
			letter-spacing: 1px;
			position: absolute;
			bottom: 10px;
			right: 10px;
			z-index: 111;
			&:hover {
				background-color: #f8f8f8;
			}
		}
		.tool {
			position: relative;
			padding-left: 5px;
			height: 20px;
			z-index: 1;
			left: 0;
			>li {
				position: relative;
				margin-left: 10px;
				float: left;
				img {
					width: 20px;
					height: 20px;
				}
				>input {
					position: absolute;
					left: 0;
					top: 0;
					width: 100%;
					height: 100%;
					opacity: 0.01;
				}
			}
		}
	}
</style>